package com.dxm.common.base.controller;

import com.dxm.common.utils.StringUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

public class BaseController {
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public static class Result<T> implements Serializable {
        //响应码
        private Integer status;
        //是否成功
        private boolean success;
        //返回值
        private T data;
        //提示信息
        private String message;
    }

    //正确响应
    public static  <T> Result OK(T data, String... message) {
        String msg = message != null && message.length > 0 ? message[0] : "";
        Result result = new Result(HttpStatus.OK.value(), true, data, msg);
        return result;
    }

    //错误响应
    public <T> Result<T> Error(String message) {
        message =  StringUtil.isEmpty(message) ? "服务器繁忙，请稍后重试" : message;
        Result result = new Result(HttpStatus.INTERNAL_SERVER_ERROR.value(), false, null, message);
        return result;
    }
    //错误响应
    public <T> Result<T> Error(HttpStatus status, String message) {
        message =  StringUtil.isEmpty(message) ? "服务器繁忙，请稍后重试" : message;
        Result result = new Result(status.value(), false, null, message);
        return result;
    }


    //获取response
    private HttpServletResponse getResponse(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        return response;
    }

    //获取request
    private HttpServletRequest getRequest(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return request;
    }

}
